package com.gitee.xiao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wang xiao
 * date 2024/7/10
 */
@Service
public class FaceDataService {

    @Autowired
    private FaceDataRepository faceDataRepository;

    // 保存人脸数据
    public FaceData saveFaceData(byte[] imageData, byte[] featureData, String description) {
        FaceData faceData = new FaceData();
        faceData.setImageData(imageData);
        faceData.setFeatureData(featureData);
        faceData.setDescription(description);
        return faceDataRepository.save(faceData);
    }

    // 通过ID获取人脸数据
    public FaceData getFaceDataById(Long id) {
        return faceDataRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("FaceData not found"));
    }

    // 计算两个人脸特征之间的欧氏距离
    private double calculateDistance(byte[] feature1, byte[] feature2) {
        // 实现欧氏距离计算，根据应用需求，计算具体方式
        // 简化版示例（实际应用中可使用更加复杂的方法）
        double sum = 0;
        for (int i = 0; i < feature1.length; i++) {
            double diff = feature1[i] - feature2[i];
            sum += diff * diff;
        }
        return Math.sqrt(sum);
    }

    // 检索最相似的人脸数据
    public FaceData findMostSimilarFace(byte[] targetFeature) {
        double minDistance = Double.MAX_VALUE;
        FaceData mostSimilarFace = null;

        for (FaceData faceData : faceDataRepository.findAll()) {
            double distance = calculateDistance(targetFeature, faceData.getFeatureData());
            if (distance < minDistance) {
                minDistance = distance;
                mostSimilarFace = faceData;
            }
        }
        return mostSimilarFace;
    }
}
